package com.cyx.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class IndexController {
    @GetMapping(value = {"/","/index"})
    public String index(Model model){
        model.addAttribute("msg","hello shiro");
        return "index";
    }

    @GetMapping("/user")
    public String user(){
        return "user";
    }

    @GetMapping("/order")
    public String order(){
        return "order";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username,String password,Model model){
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(username,password);
        try{
            subject.login(token);
            return "redirect:index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","错误的账号");
            return "/login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "/login";
        }catch (AuthenticationException  e){
            model.addAttribute("msg","认证错误");
            return "/login";
        }

    }

    @GetMapping("/order/add")
    public String addOrder(){
        return "orders/add";
    }
    @GetMapping("/order/update")
    public String updateOrder(){
        return "order/update";
    }
}
